import { Card, Button, Checkbox, Form, Input, message } from 'antd'
import logo from '../../assets/logo.png'
import './index.scss'
import { useDispatch } from 'react-redux'
import { loginAction } from '@/store/actions/login'
import { useHistory, useLocation } from 'react-router-dom'

// 表单验证
const validateAgree = (rule, value) => {
  // return value
  //   ? Promise.resolve()
  //   : Promise.reject(new Error('请勾选用户协议'))
  // console.log('函数校验', rule, value)
  if (!value) {
    return Promise.reject(new Error('请勾选用户协议'))
  }
  // 校验通过
  return Promise.resolve()
}

const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const location = useLocation()

  // 登录
  const onFinish = async (values) => {
    // 发请求登录
    try {
      await dispatch(loginAction(values))
      message.success('登录成功')
      // 跳转首页
      console.log(location)
      history.push(location.state?.from || '/home')
    } catch (error) {
      message.error(error.response.data.message)
    }
  }

  return (
    <div className="login">
      <Card className="login-container">
        {/* 极客园logo */}
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          validateTrigger={['onBlur', 'onChange']}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            agree: false,
          }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="mobile"
            rules={[
              {
                required: true,
                message: '请输入手机号!',
              },
              {
                pattern: /^1[3-9][0-9]{9}$/,
                message: '手机号码格式不对',
                validateTrigger: 'onBlur',
              },
            ]}
          >
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: '请输入验证码!',
              },
              {
                len: 6,
                message: '请输入6位验证码',
              },
            ]}
          >
            <Input.Password size="large" />
          </Form.Item>

          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator: validateAgree,
              },
            ]}
          >
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" size="large" block htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
